package com.recommendation.action;

import java.sql.Connection;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.recommendation.db.DBUtils;
import com.recommendation.db.Dao;
import com.recommendation.domain.RecommendMode;
import com.recommendation.domain.RecommendScope;
import com.recommendation.domain.SpecialItems;

@Results({
	@Result(name="success", type="httpheader"),
	@Result(name="error", type="httpheader", params={"headers.msg", "error"})
})
public class SaveOptionsAction extends ActionBase{

	private RecommendMode mode;
	private RecommendScope scope;
	private SpecialItems special;
	
	public String execute() throws Exception
	{
		_log.info("mode: " + mode);
		_log.info("scope: " + scope);
		long userId = getUserId();
		int version = getVersion();
		if (mode != null)
		{
			if (mode.getRecentPeriod() < RecommendMode.RECENT_PERIOD_MIN)
			{
				mode.setRecentPeriod(RecommendMode.RECENT_PERIOD_MIN);
			}
			if (mode.getRecentPeriod() > RecommendMode.RECENT_PERIOD_MAX)
			{
				mode.setRecentPeriod(RecommendMode.RECENT_PERIOD_MAX);
			}
		}
		Connection conn = null;
		try
		{
			conn = DBUtils.getConnection();
			conn.setAutoCommit(false);
			if (mode != null)
			{
				Dao.INSTANCE.setRecommendMode(mode, userId, conn);
			}
			Dao.INSTANCE.setRecommendScope(scope, userId, conn);
			if (version >= 2)
			{
				Dao.INSTANCE.setSpecialItems(special, userId, conn);
			}
			conn.commit();
		}
		catch (Exception e)
		{
			error(e);
			DBUtils.rollback(conn);
			return ERROR;
		}
		finally
		{
			DBUtils.close(conn, null, null);
		}
		return SUCCESS;
	}

	public void setScope(RecommendScope scope) {
		this.scope = scope;
	}
	
	public RecommendScope getScope() {
		return this.scope;
	}

	public void setSpecial(SpecialItems special) {
		this.special = special;
	}

	public SpecialItems getSpecial() {
		return special;
	}

	public void setMode(RecommendMode mode) {
		this.mode = mode;
	}

	public RecommendMode getMode() {
		return mode;
	}
}
